const express = require("express");
const cors = require("cors");
const { Server } = require("socket.io");
const mongoose = require("mongoose"); // 导入数据库
const chatRoutes = require("./routers/chatRoom"); // 引入新的路由文件
const setupSockets = require("./sockets/chatRoom"); // 引入新的 Socket.IO 文件

const app = express();

// 允许跨域请求
app.use(cors());

// 创建 HTTP 服务器
const server = require("http").createServer(app);

// 初始化 Socket.IO
const io = new Server(server, {
  cors: {
    origin: "*",
  },
});

// 建立链接
mongoose.connect("mongodb://localhost/chatroom", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

// 注册路由
app.use("/chatroom", chatRoutes); // 注册聊天相关路由

// 设置 Socket.IO
setupSockets(io);

// 启动服务器
const PORT = 4000;
server.listen(PORT, () => {
  console.log("启动!!!");
});
